package log

import (
	"io/ioutil"
	stlog "log"
	"net/http"
	"os"
)

var logger *stlog.Logger

type fileLog string

func (fl fileLog) Write(date []byte) (int, error) {
	f, err := os.OpenFile(string(fl), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)

	if err != nil {
		return 0, err
	}
	defer f.Close()
	return f.Write(date)
}

// init logger
func Run(destination string) {
	logger = stlog.New(fileLog(destination), "go", stlog.LstdFlags)
}

func RegisterHandlers() {
	// fmt.Printf("log service register handler\n")
	http.HandleFunc("/log", func(w http.ResponseWriter, r *http.Request) {
		logger.Printf("receiving request %v\n", r.URL.Path)
		switch r.Method {
		case "GET":
			logger.Println("get")
		case http.MethodPost:
			logger.Println("post")
			msg, err := ioutil.ReadAll(r.Body)
			if err != nil || len(msg) == 0 {
				w.WriteHeader(
					http.StatusBadRequest,
				)
				return
			}
			write(string(msg))
		}
	})
}

func write(msg string) {
	logger.Printf("%v\n", msg)
}
